package com.photoeditor.demo.ui.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.ui.adapter.gallery.ListGridAdapter;


/**
 * 带有快速滑动栏的listView
 * 用于相册列表
 */
public class ScrollCursorListView extends ListView {

    private OnScrollListener mScrollListener;

    private ListGridAdapter mAdapter;

    private ViewGroup mParent;

    private VerticalScrollBar mScrollBar;

    /**
     * 滑动时的回调
     */
    private VerticalScrollBar.OnScrollBarChangeListener mSeekBarListener;

    /**
     * 滑块的最大值
     */
    private final int MAX = 100000;

    private final int DELAY_TIME = 1000;

    private Handler mHandler;

    private final int MSG_CLOSE_SEEKBAR = 100;
    private final int MSG_SHOW_SEEKBAR = 101;

    private boolean mNotScroll = true;
    private boolean mStopMove = true;

    private Animation mOutAnimation;
    private Animation mInAnimation;

    public ScrollCursorListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MSG_CLOSE_SEEKBAR) {
                    if (mScrollBar != null) {
                        if (mOutAnimation == null) {
                            mOutAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.right_out);
                        }
                        if (mScrollBar.getVisibility() != View.GONE) {
                            mScrollBar.startAnimation(mOutAnimation);
                            mScrollBar.setVisibility(View.GONE);
                        }
                    }
                } else if (msg.what == MSG_SHOW_SEEKBAR) {
                    if (mScrollBar != null) {
                        if (mInAnimation == null) {
                            mInAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.left_in);
                        }
                        if (mScrollBar.getVisibility() != View.VISIBLE) {
                            mScrollBar.startAnimation(mInAnimation);
                            mScrollBar.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        };
        mScrollListener = new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState != OnScrollListener.SCROLL_STATE_IDLE) {//在滑动
                    mNotScroll = false;
                    if (mAdapter != null) {
                        if (mAdapter.getListLength() * 1.0f / getHeight() > 2.0f) {
                            mHandler.removeMessages(MSG_CLOSE_SEEKBAR);
                            mHandler.removeMessages(MSG_SHOW_SEEKBAR);
                            mHandler.sendEmptyMessage(MSG_SHOW_SEEKBAR);
                        }
                    }
                } else {
                    mNotScroll = true;
                    closeScrollBar();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                if (mAdapter != null && mScrollBar != null) {
                    if (!mSeekBarListener.isUserChange()) {
                        View v = view.getChildAt(0);
                        if (v != null) {
                            int top = v.getTop();
                            int position = view.getFirstVisiblePosition();
                            int len = mAdapter.getListLength() - getHeight();
                            top = -top + mAdapter.getPositionTopLength(position);
                            mScrollBar.setProgress((int) ((top * 1.0f / len) * MAX));
                        }
                    } else {

                        if (mScrollBar.getTextViewVisible() && !mStopMove) {
                            int position = ScrollCursorListView.this.getFirstVisiblePosition();
                            if (position >= 0) {
                                int id = mAdapter.getSectionForPosition(position);
                                mScrollBar.setText(mAdapter.getSections()[id].toString());
                            }
                        }
                    }
                }
            }
        };
        this.setOnScrollListener(mScrollListener);
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        if (adapter instanceof ListGridAdapter) {
            mAdapter = (ListGridAdapter) adapter;
            super.setAdapter(adapter);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (this.getParent() != null) {
            mParent = (ViewGroup) this.getParent();
        }
        if (mParent != null) {
            initCursorView();
        }
    }

    private void initCursorView() {
        if (mParent instanceof RelativeLayout) {
            RelativeLayout parent = (RelativeLayout) mParent;
            mScrollBar = new VerticalScrollBar(getContext());
            mScrollBar.setMax(MAX);
            mScrollBar.setProgress(0);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
            lp.topMargin = DeviceUtils.dip2px(ComponentContext.getContext(), 10);
            lp.bottomMargin = DeviceUtils.dip2px(ComponentContext.getContext(), 10);
            parent.addView(mScrollBar, lp);
            mSeekBarListener = new VerticalScrollBar.OnScrollBarChangeListener() {

                @Override
                public void onStopTrackingTouch(VerticalScrollBar scrollbar) {
                    mScrollBar.setTextViewVisible(false, null);
                    mStopMove = true;
                    closeScrollBar();
                }

                @Override
                public void onStartTrackingTouch(VerticalScrollBar scrollbar) {
                    mHandler.removeMessages(MSG_CLOSE_SEEKBAR);
                    mStopMove = false;
                    setUserChange(true);
                    String str = null;
                    int position = ScrollCursorListView.this.getFirstVisiblePosition();
                    if (position >= 0) {
                        int id = mAdapter.getSectionForPosition(position);
                        str = mAdapter.getSections()[id].toString();
                    }
                    mScrollBar.setTextViewVisible(true, str);
                }

                @Override
                public void onProgressChanged(VerticalScrollBar scrollbar, int progress,
                                              boolean fromUser) {
                    if (isUserChange()) {
                        int len = mAdapter.getListLength() - getHeight() + mAdapter.getSingleHeight();//加上getSingleHeight是为了让他顺利滑动到底部
                        int position = mAdapter.getPositionFromLength((int) (len * (progress * 1.0f / MAX)));
                        ScrollCursorListView.this.setSelection(position);
                    }
                }
            };
            mScrollBar.setOnScrollBarChangeListener(mSeekBarListener);

            mScrollBar.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            mSeekBarListener.setUserChange(false);
        }
        boolean ret = true;
        try {
            ret = super.dispatchTouchEvent(ev);
        } catch (Exception e) {
        }

        return ret;
    }

    /**
     * 关闭ScrollBar
     */
    private void closeScrollBar() {
        if (mNotScroll && mStopMove) {
            mHandler.removeMessages(MSG_CLOSE_SEEKBAR);
            mHandler.removeMessages(MSG_SHOW_SEEKBAR);
            mHandler.sendEmptyMessageDelayed(MSG_CLOSE_SEEKBAR, DELAY_TIME);
        }
    }
}
